//
//  TKNetworkManager.swift
//  TKWBOne
//
//  Created by tiankun on 16/8/31.
//  Copyright © 2016年 1. All rights reserved.
//

import UIKit
import AFNetworking

enum TKHTTPMethod {
    case GET
    case POST
}
class TKNetworkManager: AFHTTPSessionManager {
    static let shared: TKNetworkManager = {
        let instance = TKNetworkManager()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    //用户账户的懒加载属性
    lazy var userAccount = TKUserAccount()
    //用户登录标记
    var userLogon: Bool {
        return userAccount.access_token != nil
    }
    func tokenRequest(method: TKHTTPMethod = .GET, URLString: String, parameters: [String : AnyObject]?, completion: (json: AnyObject?, isSuccess: Bool)->()) {
        guard let token = userAccount.access_token else {
            print("没有token,需要登录")
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: TKUserShouldLoginNotification), object: nil)
            completion(json: nil, isSuccess: false)
            return
        }
        var parameters = parameters
        if parameters == nil {
            parameters = [String : AnyObject]()
        }
        parameters!["access_token"] = token
        request(method: method, URLSrting: URLString, parameters: parameters) { (json, isSuccess) in
            completion(json: json, isSuccess: isSuccess)
        }
    }
    func request(method: TKHTTPMethod = .GET, URLSrting: String, parameters: [String : AnyObject]?, completion: (json: AnyObject?, isSuccess: Bool)->()) {
        let success = {(task: URLSessionDataTask, json: AnyObject?)->() in
            completion(json: json, isSuccess: true)
        }
        let failure = {(task: URLSessionDataTask?, error: Error)->() in
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("token已过期")
                //FIXME: 发送通知 提醒用户重新登录
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: TKUserShouldLoginNotification), object: "token过期")
            }
            print("网络请求错误\(error)")
            completion(json: nil, isSuccess: false)
        }
        
        if method == .GET {
            get(URLSrting, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            post(URLSrting, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
